#!/usr/bin/perl
#
use strict;
use warnings;
use Data::Dumper;
 
binmode STDOUT, ":utf8";
#use utf8;
 
use JSON;
require "doa_subs.pl";

use CGI;
use lib '.';
use users;

my ($username,$level) = &validate;
my ($realm) = get_realm();
my $q = new CGI;
print $q->header;
print $q->start_html('Add Player');
print $q->h1('Player Identity');

############################## Main Prog ##############################
#
# This function will allow the user to add a players name to the player id
#
#

my $data;
my $outdata={};

my $player_id={};
my $player_name={};
my $playeralt={};
loadPlayers($player_id,$player_name,$playeralt);
my $search="";
my $allisearch="";

my %FORM;
foreach my $field ($q->param()) 
{
	$FORM{$field} = $q->param($field);
#	print $q->p($field." ".$FORM{$field});
}

if (exists $FORM{search})		# first time through
{
	$search=$FORM{search};
	$allisearch=$FORM{alli}||"None";
	print $q->start_form;
	print "Enter Player Name for ID ";
	print $q->textfield('pid', $search);
	print $q->textfield('name');
	print $q->submit('Action','Save');
	print $q->textfield('allid', $allisearch);
	print $q->end_form;
}
if (exists $FORM{name})
{
	$search=$FORM{pid};
	$allisearch=$FORM{allid};
	my $altsearch=$FORM{name};
	
	$altsearch=lc($altsearch);
	my $tpid=$playeralt->{$altsearch}||"0";
	if ( $tpid eq "0" )
	{
		$player_id->{$search}=$FORM{name};
		writePlayers($player_id);
		open my $fh, ">>:utf8", "data/addplayers".".$realm" or die_nice("can't open addPLAYERS".".$realm file to write $!");
		print $fh "$search|$FORM{name}|$allisearch\n";
		close $fh;

		print $q->br(),$q->br(),$q->p("Player name $FORM{name} added");
	}
	else
	{
		print $q->br(),$q->br(),$q->p("Player name already $FORM{name} Exists - NOT Added");
	}
}

print $q->br();
print $q->a( {-href=>"findalliance2.pl?search=$allisearch"}, "back to Alliance details");
print $q->br();
print $q->a( {-href=>"listAlliance2.pl"}, "Alliance list");

print $q->end_html;
